package com.oa.kq.ctrl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.mdp.core.entity.LangTips;
import com.mdp.core.entity.Result;
import com.mdp.core.entity.Tips;
import com.mdp.core.query.QueryTools;
import com.mdp.core.service.SequenceService;
import com.mdp.safe.client.entity.User;
import com.mdp.safe.client.utils.LoginUtils;
import com.mdp.swagger.ApiEntityParams;
import com.oa.kq.entity.Dept;
import com.oa.kq.entity.GroupDept;
import com.oa.kq.service.DeptService;
import com.oa.utils.ExcelView;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import springfox.documentation.annotations.ApiIgnore;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author maimeng-mdp code-gen
 * @since 2023年10月9日
 */
@Controller
@RequestMapping(value = "/**/oa/kq/dept")
@Api(tags = {"sys_dept-操作接口"})
public class DeptController {

    static Logger logger = LoggerFactory.getLogger(DeptController.class);

    @Autowired
    private DeptService deptService;

    @Autowired
    private SequenceService seqService;

    /**
     * 跳转到管理部门和成员页面manageDept.html
     */
    @RequestMapping(value = "/manageDept")
    public ModelAndView manageDept(Dept dept) {
        ModelAndView mv = new ModelAndView();
        Map<String, Object> deptInfo = new HashMap<>();
        deptInfo.put("dept", dept);
        mv.addAllObjects(deptInfo);
        return mv;
    }

    /**
     * 部门和成员信息
     */
    @ResponseBody
    @RequestMapping(value = "/deptMemberInfo")
    public Result deptMemberInfo(Dept dept) {
        Map<String, Object> deptInfo = deptService.getDeptInfo(dept);
        return Result.ok().setData(deptInfo);
    }

    /**
     * 部门和成员信息    拓展
     * 得到当前部门的信息，用户信息
     * 当前部门的子部门的用户信息，部门信息
     *
     * @author LinYuKun
     * @cdate 2020/01/04 15:09
     */
    @ResponseBody
    @RequestMapping(value = "/deptMemberInfoExt", method = RequestMethod.POST)
    public Result deptMemberInfoExt(@RequestBody Dept dept) {
        // todo deptService.deptMemberInfoExt方法是自己写的， 不知道怎么添加page,qw
//        PageUtils.startPage(dept);
        Map<String, Object> result = deptService.deptMemberInfoExt(dept);
//        PageUtils.responePage(m, result);
        return Result.ok("查询成功").setData(result);
    }

    /**
     * 获取所有的部门
     */
    @ResponseBody
    @RequestMapping(value = "/getAllDept")
    public List<Dept> getAllDept(String deptid) {
        return deptService.getAllDept(deptid);
    }

    /**
     * 新增部门
     */
    @ResponseBody
    @RequestMapping(value = "/insertDept")
    public Dept insertDept(Dept dept) {
        if (StringUtils.isEmpty(dept.getDeptid())) {
            dept.setDeptid(seqService.getTablePK("dept", "deptid"));
        }
        deptService.insert(dept);
        return dept;
    }

    /**
     * 获取上级部门
     */
    @ResponseBody
    @RequestMapping(value = "/getFatherDept")
    public Dept getFatherDept(String deptid) {
        return deptService.getFatherDept(deptid);
    }

    /**
     * 获取除子代以外的所有部门
     */
    @ResponseBody
    @RequestMapping(value = "/getDeptExceptSon")
    public List<Dept> getDeptExceptSon(String deptid) {
        return deptService.getDeptExceptSon(deptid);
    }

    /**
     * 判断该部门是否可以删除
     */
    @ResponseBody
    @RequestMapping(value = "/isDeleteDept")
    public boolean isDeleteDept(String deptid) {
        return deptService.isDeleteDept(deptid);
    }

    /**
     * 获取子部门：用于选择参与部门
     */
    @ResponseBody
    @RequestMapping(value = "/getChildrenDept")
    public List<Dept> getChildrenDept(String deptid) {
        return deptService.getChildrenDept(deptid);
    }

    /**
     * 获取该部门下的员工
     */
    @ResponseBody
    @RequestMapping(value = "/getDeptMember")
    public List<Map<String, Object>> getDeptMember(String deptid) {
        return deptService.getDeptMember(deptid);
    }

    /**
     * 获取根部门
     */
    @ResponseBody
    @RequestMapping(value = "/getRootDeptInfo")
    public Dept getRootDeptInfo() {
        return deptService.getRootDeptInfo();
    }

    /**
     * 根据所选择的deptid获取这些部门下的员工，包括子部门 的员工
     */
    @ResponseBody
    @RequestMapping(value = "/getAllMember")
    public List<Map<String, Object>> getAllMember(@RequestBody List<GroupDept> deptList) {
        return deptService.getAllMember(deptList);
    }


    /**
     * 跳转到查询页面listDept.jsp
     */
    @RequestMapping(value = "/listDept")
    public ModelAndView listDept(@ModelAttribute("dept") Dept dept, BindingResult result, Model model) {
        ModelAndView mv = new ModelAndView();
        mv.addObject("data", dept);
        return mv;
    }


    /**
     * 跳转到修改页面editDept.jsp
     */
    @RequestMapping(value = "/editDept")
    public ModelAndView editDept(@ModelAttribute("dept") Dept dept, BindingResult result, Model model) {
        ModelAndView mv = new ModelAndView();
        dept = deptService.selectOneObject(dept);    //根据ID读取
        mv.addObject("data", dept);
        return mv;
    }


    /**
     * 请求需带json后缀,如selectListDeptByPage.json
     * 根据条件查询数据对象列表
     */
    @RequestMapping(value = "/selectListDeptByPage")
    public ModelAndView selectListDeptByPage(@ModelAttribute("dept") Dept dept, BindingResult result, Model model) {
        ModelAndView mv = new ModelAndView();

//        List<Dept> deptList = deptService.selectListByPage(dept);    //列出Dept列表
        List<Dept> deptList = deptService.selectListByWhere(dept);    //列出Dept列表
        mv.addObject("data", deptList);
        Tips tips = new Tips("查询成功");
        mv.addObject("tips", tips);
        return mv;
    }

    /**
     * 根据主键删除1条数据
     */
    @ResponseBody
    @RequestMapping(value = "/deleteDeptByPk")
    public void deleteDeptByPk(@ModelAttribute("dept") Dept dept, BindingResult result) {
        deptService.deleteByPk(dept);
    }

    /**
     * 根据主键修改一条数据
     */
    @ResponseBody
    @RequestMapping(value = "/updateDeptByPk")
    public void updateDeptByPk(@ModelAttribute("dept") Dept dept, BindingResult result, Model model) {
        deptService.updateByPk(dept);
    }


    /**
     * 批量删除
     */
    @RequestMapping(value = "/batchDeleteDept")
    public ModelAndView batchDeleteDept(@RequestParam("deptid[]") String[] deptid) {
        ModelAndView mv = new ModelAndView();
        Tips tips = new Tips("成功删除" + deptid.length + "条数据");
        List<Dept> list = new ArrayList<Dept>();
        for (int i = 0; i < deptid.length; i++) {
            Dept dept = new Dept();
            dept.setDeptid(deptid[i]);
            list.add(dept);
        }
        deptService.batchDelete(list);
        mv.addObject("tips", tips);
        return mv;
    }

    /*
     * 导出到excel
     * @return
     */
    @RequestMapping(value = "/exportDeptToExcel")
    public ModelAndView exportDeptToExcel(@ModelAttribute("dept") Dept dept, BindingResult result, Model model) {
        ModelAndView mv = new ModelAndView();
        Tips tips = new Tips("成功导出数据");
        try {
            Map<String, Object> dataMap = new HashMap<String, Object>();
            List<String> titles = new ArrayList<String>();
            titles.add("deptid");
            titles.add("deptname");
            titles.add("pdeptid");
            dataMap.put("titles", titles);
            List<Dept> DeptList = deptService.selectListByWhere(dept);
            List<Map<String, Object>> allList = new ArrayList<Map<String, Object>>();
            for (int i = 0; i < DeptList.size(); i++) {
                Map<String, Object> row = new HashMap<String, Object>();
                row.put("var1", DeptList.get(i).getDeptid());
                row.put("var2", DeptList.get(i).getDeptName());
                row.put("var3", DeptList.get(i).getPdeptid());
                allList.add(row);
            }
            dataMap.put("varList", allList);
            com.oa.utils.ExcelView erv = new ExcelView();
            mv = new ModelAndView(erv, dataMap);
        } catch (Exception e) {
            logger.error(e.toString(), e);
            tips.setErrMsg("导出数据异常");
        }
        mv.addObject("tips", tips);
        return mv;
    }

    @ResponseBody
    @ApiOperation(value = "sys_dept-查询列表", notes = " ")
    @ApiEntityParams(Dept.class)
    @ApiResponses({@ApiResponse(code = 200, response = Dept.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'错误码'},total:总记录数,data:[数据对象1,数据对象2,...]}")})
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public Result listDept(@ApiIgnore @RequestParam Map<String, Object> params) {
        User user = LoginUtils.getCurrentUserInfo();
        QueryWrapper<Dept> qw = QueryTools.initQueryWrapper(Dept.class, params);
        IPage page = QueryTools.initPage(params);
        List<Map<String, Object>> datas = deptService.selectListMapByWhere(page, qw, params);
        return Result.ok("query-ok", "查询成功").setData(datas).setTotal(page.getTotal());
    }

    @ResponseBody
    @ApiOperation(value = "sys_dept-新增", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, response = Dept.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")})
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public Result addDept(@RequestBody Dept dept) {
        deptService.save(dept);
        return Result.ok("add-ok", "添加成功！");
    }

    @ResponseBody
    @ApiOperation(value = "sys_dept-删除", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'}}")})
    @RequestMapping(value = "/del", method = RequestMethod.POST)
    public Result delDept(@RequestBody Dept dept) {
        deptService.removeById(dept);
        return Result.ok("del-ok", "删除成功！");
    }

    @ResponseBody
    @ApiOperation(value = "sys_dept-修改", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, response = Dept.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")})
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public Result editDept(@RequestBody Dept dept) {
        deptService.updateById(dept);
        return Result.ok("edit-ok", "修改成功！");
    }

    @ResponseBody
    @ApiOperation(value = "sys_dept-批量修改某些字段", notes = "")
    @ApiEntityParams(value = Dept.class, props = {}, remark = "sys_dept", paramType = "body")
    @ApiResponses({@ApiResponse(code = 200, response = Dept.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")})
    @RequestMapping(value = "/editSomeFields", method = RequestMethod.POST)
    public Result editSomeFields(@ApiIgnore @RequestBody Map<String, Object> params) {
        User user = LoginUtils.getCurrentUserInfo();
        deptService.editSomeFields(params);
        return Result.ok("edit-ok", "更新成功");
    }

    @ResponseBody
    @ApiOperation(value = "sys_dept-批量删除", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'}")})
    @RequestMapping(value = "/batchDel", method = RequestMethod.POST)
    public Result batchDelDept(@RequestBody List<Dept> depts) {
        User user = LoginUtils.getCurrentUserInfo();
        if (depts.size() <= 0) {
            return Result.error("batchDel-data-err-0", "请上送待删除数据列表");
        }
        List<Dept> datasDb = deptService.listByIds(depts.stream().map(i -> i.getDeptid()).collect(Collectors.toList()));

        List<Dept> can = new ArrayList<>();
        List<Dept> no = new ArrayList<>();
        for (Dept data : datasDb) {
            if (true) {
                can.add(data);
            } else {
                no.add(data);
            }
        }
        List<String> msgs = new ArrayList<>();
        if (can.size() > 0) {
            deptService.removeByIds(can);
            msgs.add(LangTips.transMsg("del-ok-num", "成功删除%s条数据.", can.size()));
        }

        if (no.size() > 0) {
            msgs.add(LangTips.transMsg("not-allow-del-num", "以下%s条数据不能删除:【%s】", no.size(), no.stream().map(i -> i.getDeptid()).collect(Collectors.joining(","))));
        }
        if (can.size() > 0) {
            return Result.ok(msgs.stream().collect(Collectors.joining()));
        } else {
            return Result.error(msgs.stream().collect(Collectors.joining()));
        }
    }

    @ResponseBody
    @ApiOperation(value = "sys_dept-根据主键查询一条数据", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, response = Dept.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")})
    @RequestMapping(value = "/queryById", method = RequestMethod.GET)
    public Result queryById(Dept dept) {
        Dept data = (Dept) deptService.getById(dept);
        return Result.ok().setData(data);
    }

}
